const express = require('express')
const { Formidable } = require('formidable');
const advRouter = express.Router()
const path = require('path')
const fs = require('fs')
const advListModel = require('../db/model/advListModel')

advRouter.post('/addAdv', (request, response)=>{
    // 如何接收一个 formdata 的数据，既有普通表单属性，又有文件信息==》 formidable
    // 1. 安装 npm i formidable
    // 2. 引入
    // 3. 实例化对象，并且传入 配置项  uploadDir上传目录  keepExtensions: 是否保留扩展名
    const form = new Formidable({
        uploadDir:path.resolve(__dirname,'../public/upload'),
        keepExtensions:true
    });

    form.parse(request, async (err, fields, files) => {
        let file = files['advPic']
        console.log(file)
        if(file.size===0){
            // 说明没有传文件，删除upload中的空文件==>fs模块
            fs.unlinkSync(file.filepath)
        }else{
            // 有文件上传
            fields.advPic = file.newFilename
            console.log(fields) 
        }
        try{
            await advListModel.create(fields)
            response.json({
                code:0,
                msg:'广告添加成功'
            })
        }catch(e){
            response.json({
                code:1,
                msg:'广告添加失败'
            })
        }
    })
})

module.exports = advRouter